package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.HotDataCache;
import com.sky.constant.CacheConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Service
@Slf4j
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private CacheManager cacheManager;
    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 新增菜品和口味
     * @param dishDTO
     */
    @Transactional
    // 新增菜品后：全量删除分页缓存（所有分页数据）+ 清理对应分类的分类缓存
    @Caching(
            evict = {
                    // 第一个缓存操作：全量删除分页缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_PAGE_CACHE,
                            allEntries = true // 删除该缓存下所有数据
                    ),
                    // 第二个缓存操作：删除新增菜品所属分类的缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_CATEGORY_CACHE,
                            key = "#dishDTO.categoryId" // 按分类ID精确删除
                    )
            }
    )
    public void saveWithFlavor(DishDTO dishDTO) {
        log.info("新增菜品：{}", dishDTO);
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入1条数据
        dishMapper.insert(dish);

        //获取插入后生成的主键值
        Long dishId = dish.getId();

        //向口味表插入n条数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            flavors.forEach(flavor -> flavor.setDishId(dishId));
            //前端传入的口味数据中， dishId 属性为null，因为此时菜品还未插入数据库
            //口味数据 dishId 属性需要设置
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品分页查询
     * @param dishPageQueryDTO
     * @return
     */
    @Cacheable(
            value = CacheConstant.DISH_PAGE_CACHE, // 分页缓存专用名称
            key = "'page='+#dishPageQueryDTO.page+'-pageSize='+#dishPageQueryDTO.pageSize" +
                    "+'-categoryId='+#dishPageQueryDTO.categoryId+'-status='+#dishPageQueryDTO.status" +
                    "+'-name='+#dishPageQueryDTO.name", // 包含所有筛选参数
            condition = "#dishPageQueryDTO != null" // 过滤空参数
    )
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        Page<DishVO> page = dishMapper.pageQuery(dishPageQueryDTO);
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 批量删除菜品
     * @param ids
     */
    @Transactional
    @Caching(
            evict = {
                    // 第一个缓存操作：全量删除分页缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_PAGE_CACHE,
                            allEntries = true // 删除该缓存下所有数据
                    ),
                    // 第二个缓存操作：全量删除分类缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_CATEGORY_CACHE,
                            allEntries = true
                    ),
                    // 第三个缓存操作：删除所有菜品缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_CACHE,
                            allEntries = true
                    ),
                    // 第四个缓存操作：删除所有按类型查询缓存
                    @CacheEvict(
                            value = CacheConstant.CATEGORY_LIST_CACHE,
                            key = "1"
                    )
            }
    )
    public void deleteBatch(List<Long> ids) {
        //判断当前菜品是否能够删除——是否存在启售中的菜品
        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                //当前菜品处于起售中，不能删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //判断当前菜品是否能够删除——当前菜品是否有关联的套餐
        List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(ids);
        if (setmealIds != null && setmealIds.size() > 0){
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品数据
//        for (Long id : ids) {
//            dishMapper.deleteById(id);
//            //删除菜品关联的口味数据
//            dishFlavorMapper.deleteByDishId(id);
//        }

        //根据菜品id集合批量删除菜品数据
        //sql: delete from dish where id in (?,?,?)
        dishMapper.deleteByIds(ids);

        //根据菜品id集合批量删除菜品关联的口味数据
        //sql: delete from dish_flavor where dish_id in (?,?,?)
        dishFlavorMapper.deleteByDishIds(ids);
    }

    /**
     * 根据id查询菜品和对应的口味数据
     * @param id
     * @return
     */
    @HotDataCache(
            cacheName = CacheConstant.DISH_CACHE,
            lockWaitTime = 2,
            lockHoldTime = 10
    )
    public DishVO getByIdWithFlavor(Long id) {

        //根据id查询菜品数据
        Dish dish = dishMapper.getById(id);

        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);

        //将查询到的数据封装到vo
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     * 根据id修改菜品基本信息和口味信息
     * @param dishDTO
     */
    @Transactional
    @Caching(
            evict = {
                    // 第一个缓存操作：全量删除分页缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_PAGE_CACHE,
                            allEntries = true // 删除该缓存下所有数据
                    ),
                    // 第二个缓存操作：删除该菜品缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_CACHE,
                            key = "#dishDTO.id"
                    ),
                    // 第三个缓存操作：删除所有按类型分类查询缓存
                    @CacheEvict(
                            value = CacheConstant.CATEGORY_LIST_CACHE,
                            allEntries = true
                    ),
                    // 第四个缓存操作：删除该菜品分类缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_CATEGORY_CACHE,
                            allEntries = true
                    )
            }
    )
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品表基本信息
        dishMapper.update(dish);

        //删除原有的口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());

        //插入新的口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            flavors.forEach(flavor -> flavor.setDishId(dishDTO.getId()));
            //前端传入的口味数据中， dishId 属性为null，因为此时菜品还未插入数据库
            //口味数据 dishId 属性需要设置
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Cacheable(
            value = CacheConstant.DISH_CATEGORY_CACHE,
            key = "#categoryId",
            condition = "!T(com.sky.utils.CacheParamUtils).isInvalidCategoryId(#categoryId)"
    )
    public List<Dish> queryByCategoryId(Long categoryId) {
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        List<Dish> dishList = dishMapper.queryByCategoryId(dish);
        return dishList;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    //因为可以按名字来模糊查询，缓存key设置很麻烦，所以不建议@Cacheable
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.queryByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }

    /**
     * 菜品起售停售
     * @param status
     * @param id
     */
    @Caching(
            evict = {
                    // 第一个缓存操作：全量删除分页缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_PAGE_CACHE,
                            allEntries = true // 删除该缓存下所有数据
                    ),
                    // 第二个缓存操作：删除该菜品缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_CACHE,
                            key = "#id"
                    ),
                    // 第三个缓存操作：删除按类型查询分类缓存
                    @CacheEvict(
                            value = CacheConstant.CATEGORY_LIST_CACHE,
                            key = "1"
                    ),
                    // 第四个缓存操作：删除该分类缓存
                    @CacheEvict(
                            value = CacheConstant.DISH_CATEGORY_CACHE,
                            key = "1"
                    )
            }
    )
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .status(status)
                .id(id)
                .build();
        dishMapper.update(dish);

        //如果是停售操作，则需要将包含该菜品的套餐也停售
        if(status == StatusConstant.DISABLE){
            //查询与此菜品关联的套餐id
            List<Long> setmealIds = setmealDishMapper.getSetmealIdsByDishIds(Arrays.asList(id));
            if (setmealIds != null && setmealIds.size() > 0){
                //查询当前套餐是否启售，将启售的套餐停售
                for (Long setmealid : setmealIds) {
                    Setmeal setmeal = setmealMapper.getByID(setmealid);
                    if(setmeal.getStatus() == StatusConstant.ENABLE){
                        setmeal.setStatus(StatusConstant.DISABLE);
                        setmealMapper.update(setmeal);
                    }
                }
            }
        }
    }

    /**
     * 获取热门菜品ID列表
     * @param limit 返回记录数
     * @return 热门菜品ID列表
     */
    public List<Long> getHotDishIds(int limit) {
        return dishMapper.getHotDishIds(limit);
    }


}
